package com.cq.androidtools.jetpack.hilt

import android.app.Application
import androidx.lifecycle.ViewModel
import com.cq.base.retrofit.a.Retrofit2
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.lifecycle.HiltViewModel
import dagger.hilt.components.SingletonComponent
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit
import javax.inject.Inject
import javax.inject.Singleton

/**
 * 作者: CQ
 * 日期: 2021-06-29
 * 说明:
 */
@Module
@InstallIn(SingletonComponent::class)
class NetworkModule {
    @Singleton
    @Provides
    fun provideOkHttpClient(): OkHttpClient {
        return OkHttpClient.Builder()
            .connectTimeout(20, TimeUnit.SECONDS)
            .readTimeout(20, TimeUnit.SECONDS)
            .writeTimeout(20, TimeUnit.SECONDS)
            .build()
    }
    /**
     * okHttpClient由 Hilt自动注入
     */
    @Singleton
    @Provides
    fun provideRetrofit(okHttpClient: OkHttpClient): Retrofit {
        return Retrofit.Builder()
            .addConverterFactory(GsonConverterFactory.create())
            .baseUrl("http://example.com/")
            .client(okHttpClient)
            .build()
    }

    @Singleton
    @Provides
    fun provideRetrofit2() : Retrofit2 {
        return Retrofit2.getInstance()
    }

    @Singleton
    @Provides
    fun provideMyApplication(application: Application): MyApplication {
        return application as MyApplication
    }

}

class NetworkDriver @Inject constructor(val application: MyApplication) {
}

//ViewModel的依赖注入
@HiltViewModel
class MyViewModel @Inject constructor(val repository: Repository) : ViewModel() {
}

class Repository @Inject constructor() {
}